{% extends "base.html" %}

{% block title %}会议室列表{% endblock %}

{% block content %}
<div class="container mt-4">
    <h2>会议室列表</h2>
    <div class="row mb-3">
        <div class="col-md-4">
            <input type="text" id="searchInput" class="form-control" placeholder="搜索会议室...">
        </div>
        <div class="col-md-3">
            <select id="capacityFilter" class="form-select">
                <option value="">所有容量</option>
                <option value="1-5">1-5人</option>
                <option value="6-10">6-10人</option>
                <option value="11-20">11-20人</option>
                <option value="21+">21人以上</option>
            </select>
        </div>
        <div class="col-md-3">
            <div class="input-group">
                <input type="number" id="exactCapacity" class="form-control" min="1" placeholder="指定人数">
                <button class="btn btn-outline-secondary" type="button" id="applyCapacity">筛选</button>
            </div>
        </div>
        <div class="col-md-2">
            <button id="createRoomBtn" class="btn btn-primary w-100" style="display: none;">创建会议室</button>
        </div>
    </div>
    <div class="row" id="roomsContainer">
        <!-- 会议室卡片将通过 JavaScript 动态加载 -->
    </div>
    <nav aria-label="Page navigation" class="mt-4">
        <ul class="pagination justify-content-center" id="pagination">
            <!-- 分页控件将通过 JavaScript 动态加载 -->
        </ul>
    </nav>
</div>

<!-- Hidden input for admin status -->
<input type="hidden" id="isAdmin" value="{{ is_admin }}">

<script>
    let currentPage = 1;
    const pageSize = 12;
    const isAdmin = document.getElementById('isAdmin').value === 'True';
    
    // Show/hide create room button based on admin status
    if (isAdmin) {
        document.getElementById('createRoomBtn').style.display = 'block';
    }

    async function loadRooms(page = 1, search = '', capacityFilter = '') {
        try {
            const response = await axios.get('/api/rooms', {
                params: {
                    skip: (page - 1) * pageSize,
                    limit: pageSize,
                    search: search,
                    capacity: capacityFilter
                }
            });
            console.log('API Response:', response.data);
            const data = response.data;
            renderRooms(data.rooms);
            renderPagination(data.total, page);
        } catch (error) {
            console.error('Error loading rooms:', error);
        }
    }

    function renderRooms(rooms) {
        const container = document.getElementById('roomsContainer');
        container.innerHTML = '';
        
        if (!rooms || rooms.length === 0) {
            container.innerHTML = '<div class="col-12"><p class="text-center">没有找到符合条件的会议室</p></div>';
            return;
        }
        
        rooms.forEach(room => {
            const col = document.createElement('div');
            col.className = 'col-md-4 mb-4';
            col.innerHTML = `
                <div class="card h-100">
                    <div class="card-header bg-light">
                        <h5 class="card-title mb-0">${room.name}</h5>
                    </div>
                    <div class="card-body">
                        <div class="capacity-badge mb-2">
                            <span class="badge ${getBadgeClass(room.capacity)} fs-6">
                                <i class="bi bi-people-fill"></i> 容量: ${room.capacity}人
                            </span>
                        </div>
                        <p class="card-text">
                            <strong>位置：</strong>${room.location}<br>
                            <strong>设施：</strong>${room.facilities || '无'}<br>
                            <strong>状态：</strong>${room.is_active ? '可用' : '不可用'}
                        </p>
                        <div class="d-grid gap-2">
                            <a href="/rooms/${room.id}" class="btn btn-info">查看详情</a>
                            <a href="/meetings/create?room=${room.id}&attendees=1" class="btn btn-outline-primary">
                                <i class="bi bi-calendar-plus"></i> 立即预约
                            </a>
                            ${isAdmin ? `
                                <div class="d-flex gap-2 mt-2">
                                    <button class="btn btn-warning flex-grow-1" onclick="editRoom(${room.id})">编辑</button>
                                    <button class="btn btn-danger flex-grow-1" onclick="deleteRoom(${room.id})">删除</button>
                                </div>
                            ` : ''}
                        </div>
                    </div>
                </div>
            `;
            container.appendChild(col);
        });
    }

    function renderPagination(total, currentPage) {
        const totalPages = Math.ceil(total / pageSize);
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';
        
        if (totalPages <= 1) {
            return;
        }
        
        // Previous button
        pagination.innerHTML += `
            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${currentPage - 1}">上一页</a>
            </li>
        `;
        
        // Page numbers
        for (let i = 1; i <= totalPages; i++) {
            pagination.innerHTML += `
                <li class="page-item ${i === currentPage ? 'active' : ''}">
                    <a class="page-link" href="#" data-page="${i}">${i}</a>
                </li>
            `;
        }
        
        // Next button
        pagination.innerHTML += `
            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                <a class="page-link" href="#" data-page="${currentPage + 1}">下一页</a>
            </li>
        `;
    }

    async function editRoom(roomId) {
        window.location.href = `/rooms/${roomId}/edit`;
    }

    async function deleteRoom(roomId) {
        if (confirm('确定要删除这个会议室吗？')) {
            try {
                const response = await axios.delete(`/api/rooms/${roomId}`);
                if (response.status === 204) {
                    loadRooms(currentPage, document.getElementById('searchInput').value, document.getElementById('capacityFilter').value);
                } else {
                    alert('删除会议室失败');
                }
            } catch (error) {
                console.error('Error deleting room:', error);
                alert('删除会议室失败');
            }
        }
    }

    // Event listeners
    document.getElementById('searchInput').addEventListener('input', (e) => {
        loadRooms(1, e.target.value, document.getElementById('capacityFilter').value);
    });

    document.getElementById('capacityFilter').addEventListener('change', (e) => {
        const capacityValue = e.target.value;
        console.log('筛选容量:', capacityValue);
        loadRooms(1, document.getElementById('searchInput').value, capacityValue);
    });

    document.getElementById('pagination').addEventListener('click', (e) => {
        e.preventDefault();
        if (e.target.tagName === 'A') {
            const page = parseInt(e.target.dataset.page);
            if (page && page !== currentPage) {
                currentPage = page;
                loadRooms(page, document.getElementById('searchInput').value, document.getElementById('capacityFilter').value);
            }
        }
    });

    document.getElementById('createRoomBtn').addEventListener('click', () => {
        window.location.href = '/rooms/create';
    });

    // 处理指定人数筛选
    document.getElementById('applyCapacity').addEventListener('click', () => {
        const exactCapacity = document.getElementById('exactCapacity').value;
        if (exactCapacity && !isNaN(exactCapacity) && parseInt(exactCapacity) > 0) {
            // 清除下拉框选择
            document.getElementById('capacityFilter').value = '';
            // 应用精确容量筛选
            loadRooms(1, document.getElementById('searchInput').value, `exact:${exactCapacity}`);
        }
    });
    
    // 按Enter键触发筛选
    document.getElementById('exactCapacity').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            document.getElementById('applyCapacity').click();
        }
    });

    // 页面加载时设置token和初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 设置token
        const token = localStorage.getItem('token');
        if (token) {
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
        }
        
        // 检查URL参数是否有预设的筛选条件
        const urlParams = new URLSearchParams(window.location.search);
        const capacityParam = urlParams.get('capacity');
        const searchParam = urlParams.get('search');
        
        // 如果有预设的筛选条件，设置相应的表单值
        if (capacityParam) {
            document.getElementById('capacityFilter').value = capacityParam;
        }
        
        if (searchParam) {
            document.getElementById('searchInput').value = searchParam;
        }
        
        // 加载会议室数据，使用URL中的参数或默认值
        loadRooms(1, searchParam || '', capacityParam || '');
        
        // 初始化认证和登出按钮
        checkAuth();
        initLogoutButton();
    });

    // 根据容量获取徽章样式
    function getBadgeClass(capacity) {
        if (capacity <= 5) return 'bg-info';
        if (capacity <= 10) return 'bg-success';
        if (capacity <= 20) return 'bg-warning';
        return 'bg-danger';
    }
</script>
{% endblock %} 